#include "be_parser.h"
#include <boost/lexical_cast.hpp>

BeParser::BeParser()
{
}

BeParser::~BeParser()
{
}

std::string BeParser::returnUntill(std::string stop, std::string &line)
{
	std::string result;
	size_t pos = line.find_first_of( stop, 0 );
	if ( pos != std::string::npos )
		result = line.substr( 0, pos );

	return result;
}

std::string BeParser::returnUntillStrip(std::string stop, std::string &line)
{
	std::string result;
	size_t pos = line.find_first_of( stop, 0 );
	if ( pos != std::string::npos )
	{
		result = line.substr( 0, pos );
	

	// strip result from line
	line = line.substr( pos+1, line.size() );
	}
	return result;
}

bool BeParser::beginMatchesStrip(std::string stop, std::string &line)
{
	if ( line.size() >= stop.size() )
	{
		if ( line.substr( 0, stop.size() ) == stop )
		{
			line = line.substr( stop.size(), line.size() );
			return true;
		}
	}
	return false;
}

bool BeParser::beginMatches(std::string stop, std::string &line)
{
	if ( line.size() >= stop.size() )
	{
		if ( line.substr( 0, stop.size() ) == stop )
			return true;
	}
	return false;
}

bool BeParser::endMatches(std::string stop, std::string &line)
{
	if ( line.size() >= stop.size() )
	{
		if ( line.substr( line.size()-stop.size(), stop.size() ) == stop )
			return true;
	}

	return false;
}

bool BeParser::endMatchesStrip(std::string stop, std::string &line)
{
	if ( line.size() >= stop.size() )
	{
		if ( line.substr( line.size()-stop.size(), stop.size() ) == stop )
		{
			line = line.substr( 0, line.size()-stop.size() );
			return true;
		}
	}

	return false;
}

unsigned int BeParser::contains(unsigned int start, std::string stop, std::string &line)
{
	return line.find_first_of( stop, start );
// 	size_t pos = line.find_first_of( stop, start );
// 	if ( pos > 0 )
// 		return true;
// 
// 	return false;
}

bool BeParser::parseUnsignedInt( std::string& string, unsigned int& value )
{
	string += " ";
	const std::string str=returnUntillStrip(" ", string);
	if( str.size() > 0 )
	{
		value = boost::lexical_cast<unsigned int>(str);
		return true;
	}
	return false;
}

bool BeParser::parseFloat( std::string& string, float& value )
{
	string += " ";
	const std::string str = returnUntillStrip(" ", string);
	if( str.size() > 0 )
	{
		value = boost::lexical_cast<float>(str);
		return true;
	}
	return false;
}

bool BeParser::parseVector3( std::string& string, btVector3& value )
{
	float x,y,z;
	if( parseFloat(string, x) )
	{
		if( parseFloat(string, y) )
		{
			if( parseFloat(string, z) )
			{
				value = btVector3(x,y,z);
				return true;
			}
		}
	}
	return false;
}
